package com.zhou;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class MyAccessDataBase {
    private static String dbpath = "./data.accdb";// 路径
    private static String dbname = "";// 用户名
    private static String dbpassword = "";// 密码
    private static String url = "jdbc:access:///" + dbpath;// url

    public MyAccessDataBase() {

    }

    /**
     * 批量添加数据
     *
     * @param patents
     */
    public static void addDatas(List<Patent> patents) {
        Connection conn = connectDataBase();
        String sql = "insert into [专利] ([题目], [专利类型], [申请/专利号], [申请日期], [公开/公告号], [公开/公告日], [主分类号], [分类号], [申请/专利权人], [发明/设计人], [主申请人地址], [国别省市代码], [法律状态]) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < patents.size(); i++) {
                Patent patent = patents.get(i);
                pstmt.setString(1, patent.getTitle());
                pstmt.setString(2, patent.getPatentType());
                pstmt.setString(3, patent.getAppNum());
                pstmt.setString(4, patent.getAppDate());
                pstmt.setString(5, patent.getPubNum());
                pstmt.setString(6, patent.getPubDate());
                pstmt.setString(7, patent.getMainClassCode());
                pstmt.setString(8, patent.getClassCode());
                pstmt.setString(9, patent.getApplicantName());
                pstmt.setString(10, patent.getInvName());
                pstmt.setString(11, patent.getAppAddress());
                pstmt.setString(12, patent.getAppAreaCode());
                pstmt.setString(13, patent.getLegalStatus());
                pstmt.addBatch();

                if((i+1)%100 == 0){
                    pstmt.executeBatch();
                    pstmt.clearBatch();
                }
            }
            pstmt.executeBatch();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConnection(conn);
        }
    }

    /**
     * 连接数据库
     */
    public static Connection connectDataBase() {
        try {
            Class.forName("com.hxtt.sql.access.AccessDriver");
            return DriverManager.getConnection(url, dbname, dbpassword);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭数据库
     */
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
